package org.desktop.web.client.role.form.handler;

import java.util.Map;

import org.desktop.web.client.role.RoleService;
import org.desktop.web.client.role.RoleServiceAsync;
import org.desktop.web.client.role.form.validator.CodRoleValidator;
import org.desktop.web.client.util.Util;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.info.Info;

public class CodRoleHandler implements ValueChangeHandler<String>,KeyUpHandler {

	public class CodRoleAsyncCallback implements AsyncCallback<Boolean> {
		@Override
		public void onSuccess(Boolean arg0) {
			if(arg0){
				validator.validate(textField,CodRoleValidator.NOT_VALID_VALUE);
				return;
			}
			textField.clearInvalid();
		}

		@Override
		public void onFailure(Throwable arg0) {
			// TODO Auto-generated method stub
			
		}
	}
	private CodRoleValidator validator;
	private TextField textField ;
	public CodRoleHandler(TextField textField,CodRoleValidator validator){
		this.validator=validator;
		this.textField=textField;
	}
	
	
	private RoleServiceAsync roleService = GWT.create(RoleService.class);
	@Override
	public void onValueChange(ValueChangeEvent<String> evt) {
		Map<String, String> headers = Util.getHeaders();
		roleService.existsCodRole(headers, evt.getValue(), new CodRoleAsyncCallback());
		
	}
	@Override
	public void onKeyUp(KeyUpEvent evt) {
		roleService.existsCodRole(Util.getHeaders(), ((TextField)evt.getSource()).getCurrentValue(), new CodRoleAsyncCallback());
	}
}
